import { getOrderRefundData, applyOrderRefund } from "../../api/order";
import { uploadImg } from "../../utils/request";

Page({
  data: {
    order_id: '',
    infoData: {},
    reasonList: [],
    reasonIndex: -1,
    content: '',
    imgList: [],
    showReasonPicker: false
  },
  onLoad(options) {
    this.setData({ order_id: options.order_id });
    this.getData();
  },
  getData() {
    getOrderRefundData(this.data.order_id).then(res => {
      const list = [];
      for (let item of res.refund_reason_list) {
        list.push({
          value: item,
          name: item,
          checked: false
        })
      }
      this.setData({ infoData: res || {}, reasonList: list });
    })
  },
  handleInput(e) {
    this.setData({
      content: e.detail.value
    })
  },
  handleUpload() {
    const that = this;
    uploadImg(function (url) {
      console.log(url);
      if (url) {
        const list = [...that.data.imgList];
        list.push(url);
        that.setData({
          imgList: list
        })
      }
    });
  },
  submit() {
    const { order_id, infoData, reasonList, reasonIndex, content, imgList } = this.data;
    if (reasonIndex < 0) {
      my.showToast({
        type: 'none',
        content: '请选择申请原因',
        duration: 2000
      });
      return
    }
    if (!content) {
      my.showToast({
        type: 'none',
        content: '申请说明必填',
        duration: 2000
      });
      return
    }
    const { mobile: user_mobile, paid_rent: refund_amount } = infoData;
    applyOrderRefund({
      order_id,
      user_mobile,
      refund_amount,
      refund_reason: reasonList[reasonIndex].value,
      refund_desc: content,
      refund_image: imgList.join(',')
    }).then(res => {
      my.showToast({
        type: 'success',
        content: '操作成功',
        duration: 3000
      });
      const pages = getCurrentPages();
      const beforePage = pages[pages.length - 2];
      if (beforePage.data.page) {
        beforePage.getList();
      } else {
        beforePage.getData();
      }
      my.navigateBack();
    })
  },
  closeReasonPicker() {
    this.setData({
      showReasonPicker: false
    })
  },
  openReasonPicker() {
    this.setData({
      showReasonPicker: true
    })
  },
  setReason(value) {
    this.setData({ reasonIndex: value, showReasonPicker: false });
  },
  delImg(e) {
    const index = e.currentTarget.dataset.index;
    const { imgList } = this.data;
    imgList.splice(index, 1);
    this.setData({ imgList });
  }
});
